/**
 * Created by tanbingqin on 2020/3/31.
 */
import React from 'react'
import { connect } from 'react-redux';
import config from 'config'
import {messages, deepCopy, deepFullCopy, queryCurrencyPrecision} from 'share/common'
import {Input, Row, Col, Table, Popover, Affix, Button, Radio, message, Icon, InputNumber, Popconfirm, Tag} from 'antd'
import ExpenseAmount from 'containers/request/new-request/expense-amount'
const RadioGroup = Radio.Group;
const { TextArea } = Input;
import Chooser from 'components/chooser'
import chooserData from 'share/chooserData'
import requestService from 'containers/request/request.service'
import noExpense from 'images/no-expense.png';
import Importer from 'components/template/importer/index';

class ExpenseTypeBlock extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tableLoading: {} //每个费用的分摊table的loading
    }
  }

  componentDidMount() {
    const { defaultScrollTop } = this.props;
    if (this.refs.expenseBlockRef && defaultScrollTop) {
      this.refs.expenseBlockRef.scrollTop = defaultScrollTop;
    }
  }

  //修改币种金额
  handleChangeAmountCurrency = (value, expenseIndex) => {
    const { expenseList, onChange } = this.props;
    let newExpenseList = JSON.parse(JSON.stringify(expenseList));
    newExpenseList[expenseIndex].currencyCode = value.currencyCode;
    newExpenseList[expenseIndex].amount = value.amount;
    newExpenseList[expenseIndex].actualCurrencyRate = value.actualCurrencyRate;
    newExpenseList[expenseIndex].companyCurrencyRate = value.companyCurrencyRate;
    newExpenseList[expenseIndex].rateDeviation = value.rateDeviation;

    if (newExpenseList[expenseIndex].apportionEnabled) {
      //按照比例重新计算分摊金额
      let amount = newExpenseList[expenseIndex].amount || 0;
      let expenseCurrencyCode = newExpenseList[expenseIndex].currencyCode || this.props.currencyCode;
      let apportionList = newExpenseList[expenseIndex].apportionList || [];
      apportionList.forEach((oneApportion, index) => {
        //默认分摊另外处理
        if (index !== 0) {
          oneApportion.amount = Number((amount * oneApportion.scale / 100).toFixed(queryCurrencyPrecision(expenseCurrencyCode)));
          amount -= oneApportion.amount;
        }
      });
      apportionList[0].amount = Number(Number(amount).toFixed(queryCurrencyPrecision(expenseCurrencyCode)));
      onChange && onChange(newExpenseList);
    } else {
      onChange && onChange(newExpenseList);
    }
  };

  //修改个人支付方式
  handlePaymentTypeChange = (value, expenseIndex) => {
    const { expenseList, onChange } = this.props;
    let newExpenseList = JSON.parse(JSON.stringify(expenseList));
    newExpenseList[expenseIndex].paymentType = value;
    onChange && onChange(newExpenseList);
  };

  //修改备注
  handleRemarkChange = (value, expenseIndex) => {
    const { expenseList, onChange } = this.props;
    if (value.length > 1000) {
      message.error(messages('common.max.characters.length',{arg1: 1000})/*最多输入{arg1}个字符*/);
    } else {
      let newExpenseList = JSON.parse(JSON.stringify(expenseList));
      newExpenseList[expenseIndex].remark = value;
      onChange && onChange(newExpenseList);
    }
  };

  handleNewExpenseApportion = (expenseIndex) => {
    const { expenseList, onChange, template } = this.props;
    let newExpenseList = JSON.parse(JSON.stringify(expenseList));
    let apportionItem = JSON.parse(JSON.stringify(template));
    newExpenseList[expenseIndex].apportionList.push(apportionItem);
    onChange && onChange(newExpenseList);
  };

  handleDivideExpenseApportion = (expenseIndex) => {
    const { expenseList, onChange } = this.props;
    let newExpenseList = JSON.parse(JSON.stringify(expenseList));
    let apportionList = newExpenseList[expenseIndex].apportionList;
    let currencyCode = newExpenseList[expenseIndex].currencyCode;
    let totalAmount = newExpenseList[expenseIndex].amount;
    let amount = newExpenseList[expenseIndex].amount;
    let scale = 100;
    let length = apportionList.length;
    apportionList.forEach((oneApportion, index) => {
      //余差塞入分摊最后一行
      if (index !== length - 1) {
        oneApportion.amount = Number((totalAmount / length).toFixed(queryCurrencyPrecision(currencyCode)));
        oneApportion.scale = Number((oneApportion.amount / totalAmount * 100).toFixed(2));
        amount -= oneApportion.amount;
        scale -= oneApportion.scale;
      }
    });
    apportionList[length - 1].amount = amount;
    apportionList[length - 1].scale = scale;
    onChange && onChange(newExpenseList);
  };

  copyApportion = (tableIndex, expenseIndex) => {
    const { expenseList, onChange } = this.props;
    let newExpenseList = JSON.parse(JSON.stringify(expenseList));
    let apportionItem = JSON.parse(JSON.stringify(newExpenseList[expenseIndex].apportionList[tableIndex]));
    apportionItem.amount = 0;
    apportionItem.scale = 0;
    apportionItem.defaultApportion = false;
    apportionItem.apportionmentOID = ''; //复制分摊行id要置空
    apportionItem.budgetCheckMessage = '';
    apportionItem.budgetLabelCode = '';
    newExpenseList[expenseIndex].apportionList.push(apportionItem);
    onChange && onChange(newExpenseList);
  };

  deleteApportion = (tableIndex, expenseIndex) => {
    const { currencyCode } = this.props;
    const { expenseList, onChange } = this.props;
    let newExpenseList = JSON.parse(JSON.stringify(expenseList));
    let amount = newExpenseList[expenseIndex].amount || 0;
    let expenseCurrencyCode = newExpenseList[expenseIndex].currencyCode || currencyCode;
    let apportionList = newExpenseList[expenseIndex].apportionList;
    apportionList.splice(tableIndex, 1);
    apportionList[0].amount = this.getDefaultAmountOrScale('amount', apportionList, amount, expenseCurrencyCode);
    apportionList[0].scale = this.getDefaultAmountOrScale('scale', apportionList, amount, expenseCurrencyCode);
    onChange && onChange(newExpenseList);
  };

  /**
   *
   * @param value
   * @param type amount金额 scale比例
   * @param tableIndex 分摊行的序号
   * @param expenseIndex 费用行的序号
   */
  handleChangeAmountOrScale = (value, type, tableIndex, expenseIndex) => {
    const { currencyCode } = this.props;
    const { expenseList, onChange } = this.props;
    let newExpenseList = JSON.parse(JSON.stringify(expenseList));
    let amount = newExpenseList[expenseIndex].amount || 0;
    let expenseCurrencyCode = newExpenseList[expenseIndex].currencyCode || currencyCode;
    let apportionList = newExpenseList[expenseIndex].apportionList;
    if (!isNaN(value) && value !== null && value !== undefined && value !== '' && amount !== 0) {
      //修改金额
      if (type === 'amount') {
        let defaultAmount = amount;
        apportionList[tableIndex].amount = value;
        defaultAmount = this.getDefaultAmountOrScale('amount', apportionList, amount, expenseCurrencyCode);
        if (defaultAmount < 0) {
          apportionList[tableIndex].amount = 0;
          //重算默认分摊的金额
          apportionList[0].amount = this.getDefaultAmountOrScale('amount', apportionList, amount, expenseCurrencyCode);
        } else {
          apportionList[0].amount = defaultAmount;
        }
        //重算比例
        apportionList[tableIndex].scale = Number((apportionList[tableIndex].amount * 100 / amount).toFixed(2));
        apportionList[0].scale = this.getDefaultAmountOrScale('scale', apportionList, amount, expenseCurrencyCode);
        onChange && onChange(newExpenseList);
      }
      //修改比例
      if (type === 'scale') {
        let defaultScale = 100;
        apportionList[tableIndex].scale = value;
        defaultScale = this.getDefaultAmountOrScale('scale', apportionList, amount, expenseCurrencyCode);
        if (defaultScale < 0) {
          apportionList[tableIndex].scale = 0;
          //重算默认分摊的比例
          apportionList[0].scale = this.getDefaultAmountOrScale('scale', apportionList, amount, expenseCurrencyCode);
        } else {
          apportionList[0].scale = defaultScale;
        }
        //重算金额
        apportionList[tableIndex].amount = Number((amount * apportionList[tableIndex].scale / 100).toFixed(queryCurrencyPrecision(expenseCurrencyCode)));
        apportionList[0].amount = this.getDefaultAmountOrScale('amount', apportionList, amount, expenseCurrencyCode);
        onChange && onChange(newExpenseList);
      }
    }
  };

  //计算默认分摊的金额或者比例
  /**
   *
   * @param type amount金额 scale比例
   * @param apportionList 分摊列表
   * @param amount 该费用类型的金额
   * @param currencyCode 该费用类型的币种
   */
  getDefaultAmountOrScale = (type, apportionList, amount, currencyCode) => {
    let defaultAmount = amount;
    let defaultScale = 100;
    apportionList && apportionList.forEach((oneApportion, index) => {
      if (index !== 0) {
        defaultAmount -= oneApportion.amount;
        defaultScale -= oneApportion.scale;
      }
    });
    if (type === 'amount') {
      return Number(defaultAmount.toFixed(queryCurrencyPrecision(currencyCode)));
    }
    if (type === 'scale') {
      return Number(defaultScale.toFixed(2));
    }
  };

  /**
   *
   * @param e valueOID
   * @param all valueItem
   * @param index 分摊行的序号
   * @param type 1部门 0成本中心
   * @param expenseIndex 费用行的序号
   * @param costCenter 成本中心OID
   */
  checkedChange = (e, all, index, type, expenseIndex, costCenter) => {
    const { newProfile, user, expenseList, onChange } = this.props;
    const { jobInfo, companyOID } = this.props.params;
    const { tableLoading } = this.state;
    let newExpenseList = JSON.parse(JSON.stringify(expenseList));
    let expenseTypeOID = newExpenseList[expenseIndex].expenseTypeOID;
    let apportionList = newExpenseList[expenseIndex].apportionList;
    let isChangeDepartment = false;
    let isChangeFatherCostCenter = false;
    let parentCostCenterOID = '';
    apportionList[index].costCenterItems.forEach(costCenterItem => {
      //处理分摊中部门更改
      if (costCenterItem.type === type && type === 1 && e !== costCenterItem.costCenterOID) {
        isChangeDepartment = true;
        if (e) {
          costCenterItem.costCenterOID = all.departmentOid;
          costCenterItem.name = (newProfile && newProfile['department'] && newProfile['department']['fullPathDisabled'] === 'true') ? all.name :
            all.path ? all.path : all.name;
          costCenterItem.pathDepth = all.path ? all.path.split('|').length : costCenterItem.pathDepth ? costCenterItem.pathDepth : 1;
        } else {
          costCenterItem.costCenterOID = '';
          costCenterItem.name = '';
          costCenterItem.pathDepth = 1;
        }
      }
      //处理分摊中成本中心更改
      if (costCenterItem.type === type && type === 0 && costCenterItem.costCenter === costCenter && costCenter && e !== costCenterItem.costCenterOID) {
        if (e) {
          costCenterItem.costCenterOID = all.costCenterItemOID;
          costCenterItem.name = all.name;
        } else {
          costCenterItem.costCenterOID = '';
          costCenterItem.name = '';
        }
        if (costCenterItem.costCenterType === 'father') {
          isChangeFatherCostCenter = true;
          parentCostCenterOID = costCenterItem.costCenterOID;
        }
      }
    });
    if (isChangeFatherCostCenter) {
      apportionList[index].costCenterItems.forEach(costCenterItem => {
        //处理子成本中心的parentCostCenterOID & 清空子成本中心项
        if (costCenterItem.type === 0 && costCenterItem.costCenterType === 'son') {
          costCenterItem.parentCostCenterOID = parentCostCenterOID;
          costCenterItem.costCenterOID = '';
          costCenterItem.name = '';
        }
      });
    }
    if (isChangeDepartment) {
      tableLoading[expenseTypeOID] = true;
      this.setState({tableLoading});
      let params = {
        userOID: user.userOID,
        departmentOID: e || jobInfo.departmentOID,
        companyOID,
        costCenterItemOIDs: []
      };
      apportionList[index].costCenterItems.forEach(costCenterItem => {
        if (costCenterItem.type === 0 && costCenterItem.costCenterOID) {
          params.costCenterItemOIDs.push(costCenterItem.costCenterOID);
        }
      });
      requestService.checkCostCenterNeedEmptyV2(params).then(res => {
        //res.data中为false说明是不可见，要清空成本中心项
        if (res.data) {
          apportionList[index].costCenterItems.forEach(costCenterItem => {
            //清空成本中心项
            if (costCenterItem.type === 0 && !res.data[costCenterItem.costCenterOID] && costCenterItem.costCenterOID) {
              costCenterItem.costCenterOID = '';
              costCenterItem.name = '';
              if (costCenterItem.costCenterType === 'son' && costCenterItem.parentCostCenterOID && !res.data[costCenterItem.parentCostCenterOID]) {
                costCenterItem.parentCostCenterOID = '';
              }
            }
          });
        }
        onChange && onChange(newExpenseList);
      }).finally(() => {
        tableLoading[expenseTypeOID] = false;
        this.setState({tableLoading});
      });
    } else {
      onChange && onChange(newExpenseList);
    }
  };

  processColumns = (expenseTypeOID, currencyCode, expenseIndex) => {
    const { user, newProfile } = this.props;
    const { jobInfo, companyOID, departmentOID } = this.props.params;
    let expenseApportionColumns = [
      {title: messages('request-1.key277')/*分摊项*/, dataIndex: 'costCenterItems', render: (value, record, tableIndex) => {
        let lineDepartmentOID = ''; //分摊行上部门
        value && value.map(item => {
          if (item.type === 1) {
            lineDepartmentOID = item.costCenterOID;
          }
        });
        return (
          <div>
            {record.budgetLabelCode === 'BUD_002' && <Tag color="red">{messages('request-1.key278')/*超预算*/}</Tag>}
            {record.budgetLabelCode === 'BUD_003' && <Tag color="blue">{messages('request-1.key279')/*预算预警*/}</Tag>}
            {
              value.map((oneApportion, index) => {
                let chooserItem = null;
                let leafEnable = !React.Component.prototype.checkFunctionProfiles('department.leaf.selection.required', [undefined, false]);
                //部门
                if (oneApportion.type === 1) {
                  chooserItem = deepFullCopy(chooserData['department']);
                  chooserItem.url += `?leafEnable=${leafEnable}`;
                  if (newProfile && newProfile['department'] && newProfile['department']['fullPathDisabled'] === 'true') {
                    oneApportion.value = oneApportion.name ? [{name: oneApportion.name, departmentOid: oneApportion.costCenterOID}] : undefined;
                  } else {
                    oneApportion.value = oneApportion.name ? [{path: oneApportion.name, departmentOid: oneApportion.costCenterOID}] : undefined;
                  }
                  chooserItem.columns.map(item => {
                    if (item.dataIndex === 'name') {
                      item.render = (value, record) => {
                        let departmentOID = jobInfo.departmentOID;
                        let message = '';
                        if ((!departmentOID && user.departmentOID === record.departmentOid) || (departmentOID && departmentOID === record.departmentOid)) {
                          message = messages('request-1.key294')/*(我的)*/;
                        }
                        if(newProfile && newProfile['department'] && newProfile['department']['fullPathDisabled'] !== 'true'){
                          return (
                            <Popover
                              placement="topLeft"
                              content={`${message}${record.path}`}>
                              {message}{record.path}
                            </Popover>
                          );
                        }
                        return (
                          <Popover
                            placement="topLeft"
                            content={`${message}${record.name}`}>
                            {message}{record.name}
                          </Popover>
                        );
                      };
                    }
                  });
                }
                //成本中心
                if (oneApportion.type === 0) {
                  chooserItem = deepFullCopy(chooserData['cost_center_item']);
                  chooserItem.url = `${config.baseUrl}/api/my/cost/center/items`;
                  oneApportion.value = oneApportion.name ? [{name: oneApportion.name, costCenterItemOID: oneApportion.costCenterOID}] : undefined;
                }
                return oneApportion.isApportionItem ? (
                    <div key={index}>
                      {oneApportion.type === 1 && (
                        <Row type="flex" align="middle" style={{marginBottom: 5}}>
                          <Col span={4} className="expense-apportion-name">
                            <Popover content={oneApportion.fieldName}><span className="required" />{oneApportion.fieldName}</Popover>
                          </Col>
                          <Col span={20} className="expense-apportion-chooser">
                            <Chooser
                              selectorItem={chooserItem}
                              valueKey="departmentOid"
                              labelKey={(newProfile && newProfile['department'] && newProfile['department']['fullPathDisabled'] === 'true') ? 'name' : 'path'}
                              onlyNeed="departmentOid"
                              listExtraParams={{companyOID}}
                              value={oneApportion.value}
                              onChange={(e, all) => {
                                this.checkedChange(e, all, tableIndex, oneApportion.type, expenseIndex)
                              }}
                              single
                            />
                          </Col>
                        </Row>
                      )}
                      {oneApportion.type === 0 && (
                        <Row type="flex" align="middle" style={{marginBottom: 5}}>
                          <Col span={4} className="expense-apportion-name">
                            <Popover content={oneApportion.fieldName}>
                              {oneApportion.required && <span className="required" />}{oneApportion.fieldName}
                            </Popover>
                          </Col>
                          <Col span={20} className="expense-apportion-chooser">
                            <Chooser
                              selectorItem={chooserItem}
                              valueKey="costCenterItemOID"
                              labelKey="name"
                              onlyNeed="costCenterItemOID"
                              listExtraParams={{
                                costCenterOID: oneApportion.costCenter,
                                userOID: user.userOID,
                                companyOID,
                                departmentOID: lineDepartmentOID || departmentOID,
                                expenseTypeOID,
                                parentCostCenterItemOID: oneApportion.costCenterType === 'son' ? oneApportion.parentCostCenterOID : undefined
                              }}
                              value={oneApportion.value}
                              disabled={oneApportion.costCenterType === 'son' && !oneApportion.parentCostCenterOID}
                              onChange={(e, all) => {
                                this.checkedChange(e, all, tableIndex, oneApportion.type, expenseIndex, oneApportion.costCenter)
                              }}
                              single
                            />
                          </Col>
                        </Row>
                      )}
                    </div>
                  ) : (<div />)
              })
            }
          </div>
        );
      }},
      {title: messages('request-1.key280')/*分摊金额*/, dataIndex: 'amount', width: '20%', render: (value, record, tableIndex) => {
        return (
          <InputNumber
            size="small"
            min={0}
            precision={queryCurrencyPrecision(currencyCode)}
            step={1}
            disabled={tableIndex === 0}
            value={value}
            onChange={(num) => {this.handleChangeAmountOrScale(num, 'amount', tableIndex, expenseIndex)}}
            placeholder={messages('common.please.input')/*请输入*/}
            style={{width:'100%'}}
          />
        )
      }},
      {title: messages('request-1.key281')/*分摊比例%*/, dataIndex: 'scale', width: '15%', render: (value, record, tableIndex) => {
        return (
          <InputNumber
            size="small"
            min={0}
            precision={2}
            step={1}
            disabled={tableIndex === 0}
            value={value}
            onChange={(num) => {this.handleChangeAmountOrScale(num, 'scale', tableIndex, expenseIndex)}}
            placeholder={messages('common.please.input')/*请输入*/}
            style={{width:'100%'}}
          />
        )
      }},
      {title: messages('common.operation')/*操作*/, dataIndex: 'index', width: '20%', render: (value, record, tableIndex) => {
        return (
          <span>
            <a onClick={(e) => {e.stopPropagation(); this.copyApportion(tableIndex, expenseIndex);}}>{messages('common.copy')/*复制*/}</a>&nbsp;&nbsp;&nbsp;
            {tableIndex !== 0 && (
              <a onClick={(e) => {e.stopPropagation(); this.deleteApportion(tableIndex, expenseIndex);}}>{messages('common.delete')/*删除*/}</a>
            )}
          </span>
        )
      }}
    ];
    return expenseApportionColumns;
  };

  removeExpense = (expenseIndex) => {
    const { expenseList, onChange } = this.props;

    //给删除功能增加动画特效
    let newExpenseList = JSON.parse(JSON.stringify(expenseList));
    newExpenseList[expenseIndex].removed = true;
    onChange && onChange(newExpenseList);

    setTimeout(() => {
      newExpenseList.splice(expenseIndex, 1);
      onChange && onChange(newExpenseList);
    }, 350);//动画效果设置的是300ms
  };

  goToAdd = () => {
    const { handleAdd } = this.props;
    handleAdd && handleAdd();
  };

  //isDisabled 是否禁止切换费用类型
  handleChangeOne = (expenseIndex, isDisabled) => {
    const { handleOne } = this.props;
    let currentScrollTop = this.refs.expenseBlockRef.scrollTop;
    !isDisabled && handleOne && handleOne(expenseIndex, currentScrollTop);
  };

  //返回值列表控件所需的selectorItem
  getCustSelectorItem = (reimbursementTypeField) => {
    let selectorItem = deepFullCopy(chooserData['multi_cust_list']);
    let OID = reimbursementTypeField.customEnumerationOID;
    selectorItem.title = reimbursementTypeField.name;
    selectorItem.url = `${config.baseUrl}/api/custom/enumerations/${OID}/items/v2`;
    return selectorItem;
  };

  //选择报销类型
  checkedCustChange = (e, all, expenseIndex) => {
    const { expenseList, onChange } = this.props;
    let newExpenseList = JSON.parse(JSON.stringify(expenseList));
    let reimbursementTypeField = newExpenseList[expenseIndex].reimbursementTypeField;
    reimbursementTypeField.value = all ? all.value : '';
    reimbursementTypeField.showValue = all ? all.messageKey : '';
    onChange && onChange(newExpenseList);
  };

  //处理导入分摊的回调
  handelImportCallBack = (result, expenseIndex) => {
    let resultDom = null;
    if (result.success) {
      result.message && message.info(result.message);
      resultDom = (
        <div>{messages('request-1.key295',{arg1: result.result.length})/*导入成功：{arg1}条*/}</div>
      );
      if (result.result.length > 0) {
        const { expenseList, onChange } = this.props;
        let newExpenseList = JSON.parse(JSON.stringify(expenseList));
        let expense = newExpenseList[expenseIndex];
        expense.apportionList = result.result;
        onChange && onChange(newExpenseList);
      }
    } else {
      let errorColumns = [
        {
          title: messages('request-1.key296')/*行号*/,
          dataIndex: 'rowNum',
          width: '13%'
        },
        {
          title: messages('request-1.key297')/*错误信息*/,
          dataIndex: 'errorMessage',
          render: (value) => <Popover content={value}>{value}</Popover>
        }];
      resultDom = (
        <div>
          <div>
            {
              result.result[0].rowNum === '-'
                ? <section>{messages('request-1.key298')/*导入失败*/}</section>
                : <section>
                  {result.result.length}{messages('request-1.key299')/*行导致导入失败*/}
                  {messages('request-1.key300')/*请修改后重新导入*/}
                </section>
            }
          </div>
          <div>
            <Table
              rowKey={record => record.index}
              columns={errorColumns}
              dataSource={result.result}
              pagination={false}
              bordered
              size="small"
            />
          </div>
        </div>
      );
    }
    return resultDom;
  };

  render() {
    const { expenseList, currencyList, currencyCode, isHidePaymentType, isShowDelete, disabledCurrency } = this.props;
    const { tableLoading } = this.state;
    const { entityOID, formOID } = this.props.params;
    return (
      <div className="expense-type-block" ref="expenseBlockRef">
        {expenseList.map((expense, expenseIndex) => {
          let custField = expense.reimbursementTypeField;
          return (
            <div className={`expense-item ${expenseIndex !== 0 ? 'margin-top-20' : ''} ${expense.removed ? 'removed' : ''}`}>
              {isShowDelete && (
                <Row className="header" type="flex" align="middle">
                  <Col span={12} className="header-left">{messages('request-1.key301',{arg1: expenseIndex+1})/*明细{arg1}*/}</Col>
                  <Col span={12} className="header-right">
                    <Popconfirm title={messages('common.confirm.delete')/*确定要删除吗？*/} onConfirm={() => this.removeExpense(expenseIndex)}>
                      <span style={{cursor: 'pointer'}} onClick={(e) => {e.stopPropagation()}}><Icon type="delete" />&nbsp;{messages('common.delete')/*删除*/}</span>
                    </Popconfirm>
                  </Col>
                </Row>
              )}
              <div className="content">
                <Row type="flex" align="middle">
                  <Col span={5}>{messages('request-1.key302')/*已选类型*/}:</Col>
                  <Col span={11}>
                    <div
                      className={`icon-block ${expense.expenseTypeUneditable || expense.uneditable ? 'icon-disabled' : ''}`}
                      onClick={() => this.handleChangeOne(expenseIndex, expense.expenseTypeUneditable || expense.uneditable)}
                    >
                      <img src={expense.iconURL} className="icon-img" />
                      <span className="icon-name">{expense.name}</span>
                      <Icon type="down" className="icon-down" />
                    </div>
                  </Col>
                </Row>
                <Row type="flex" align="middle">
                  <Col span={5}>{messages('request-1.key303')/*币种金额*/}:</Col>
                  <Col span={11}>
                    <ExpenseAmount
                      currencyList={currencyList}
                      value={{
                        currencyCode: expense.currencyCode || currencyCode,
                        amount: expense.amount,
                        actualCurrencyRate: expense.actualCurrencyRate || 1, //汇率
                        companyCurrencyRate: expense.companyCurrencyRate || 1, //企业汇率
                        rateDeviation: 0 //汇率偏移
                      }}
                      onChange={(value) => this.handleChangeAmountCurrency(value, expenseIndex)}
                      disabledCurrency={disabledCurrency || expense.currencyUneditable || expense.uneditable}
                      disabledAmount={expense.amountUneditable || expense.uneditable}
                    />
                  </Col>
                </Row>
                {!isHidePaymentType && (
                  <Row>
                    <Col span={5}>{messages('request-1.key291')/*支付方式*/}:</Col>
                    <Col span={11}>
                      <RadioGroup
                        value={expense.paymentType}
                        onChange={e => this.handlePaymentTypeChange(e.target.value, expenseIndex)}
                        disabled={expense.paymentTypeUneditable || expense.uneditable}
                      >
                        <Radio value={1001}>{messages('request-1.key292')/*个人支付*/}</Radio>
                        <Radio style={{marginLeft: 50}} value={1002}>{messages('request-1.key293')/*公司支付*/}</Radio>
                      </RadioGroup>
                    </Col>
                  </Row>
                )}
                {custField && custField.showOnList && (
                  <Row type="flex" align="middle">
                    <Col span={5} className={`${custField.required ? 'required' : ''}`}>{custField.name}:</Col>
                    <Col span={11}>
                      <Chooser
                        selectorItem={this.getCustSelectorItem(custField)}
                        valueKey="value"
                        labelKey="messageKey"
                        onlyNeed="value"
                        value={custField.value ? [{messageKey: custField.showValue, value: custField.value}] : undefined}
                        onChange={(e, all) => this.checkedCustChange(e, all, expenseIndex)}
                        single
                      />
                    </Col>
                  </Row>
                )}
                <Row>
                  <Col span={5}>{messages('request-1.key200')/*备注temp*/}:</Col>
                  <Col span={11}>
                    <TextArea
                      rows={4}
                      placeholder={messages('common.max.characters.length',{arg1: 1000})/*最多输入{arg1}个字符*/}
                      style={{resize: 'none'}}
                      value={expense.remark}
                      onChange={e => this.handleRemarkChange(e.target.value, expenseIndex)}
                    />
                  </Col>
                </Row>
                {expense.apportionEnabled && (
                  <Row>
                    <Col span={5}>{messages('request-1.key304')/*分摊*/}:</Col>
                    <Col span={19}>
                      <Table
                        rowKey={(record, index) => index}
                        columns={this.processColumns(expense.expenseTypeOID, expense.currencyCode || currencyCode, expenseIndex)}
                        loading={tableLoading[expense.expenseTypeOID]}
                        dataSource={expense.apportionList}
                        pagination={false}
                        style={{width:'100%'}}
                        bordered
                        size="small"
                        footer={() => {return (
                          <Row gutter={8} style={{marginBottom: 0}}>
                            <Col span={8}>
                              <Button
                                type="dashed"
                                style={{width: '100%', height: 32}}
                                onClick={() => this.handleNewExpenseApportion(expenseIndex)}
                              >
                                {messages('request-1.key305')/*新建分摊*/}
                              </Button>
                            </Col>
                            <Col span={8} className="expense-apportion-btn">
                              <Importer
                                triggerNode={<Button type="dashed" disabled={!expense.amount} style={{width: '100%', height: 32}}>{messages('request-1.key306')/*导入分摊*/}</Button>}
                                templateOptions={{
                                  templateList: [{
                                    templateName: messages('request-1.key307')/*下载EXCEL文件*/,
                                    downloadUrl: `/api/application/budget/apportionment/template/export?applicationOID=${entityOID || ''}&formOID=${formOID}`,
                                    downFileName: messages('request-1.key308')/*分摊模板文件*/
                                  }]
                                }}
                                uploadOptions={{
                                  uploadUrl: `/api/application/budget/apportionment/import?applicationOID=${entityOID || ''}&formOID=${formOID}`,
                                  uploadParams: {
                                    currencyCode: expense.currencyCode || currencyCode,
                                    amount: expense.amount,
                                    expenseTypeOID: expense.expenseTypeOID
                                  }
                                }}
                                errorTableData={(result) => this.handelImportCallBack(result, expenseIndex)}
                              />
                            </Col>
                            <Col span={8}>
                              <Button
                                type="dashed"
                                style={{width: '100%', height: 32}}
                                onClick={() => this.handleDivideExpenseApportion(expenseIndex)}
                              >
                                {messages('request-1.key309')/*一键均摊*/}
                              </Button>
                            </Col>
                          </Row>
                        )}}
                      />
                    </Col>
                  </Row>
                )}
              </div>
            </div>
          )
        })}
        {(!expenseList || !expenseList.length) && (
          <div className="no-expense-block">
            <img src={noExpense}/>
            <p>{messages('request-1.key310')/*什么都还没有~*/}</p>
            <Button type='primary' onClick={this.goToAdd}>{messages('request-1.key311')/*去添加*/}</Button>
          </div>
        )}
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company, //申请人所在公司
    user: state.login.user, //申请人
    newProfile: state.login.options,
  }
}

ExpenseTypeBlock.propTypes = {
  template: React.PropTypes.object, //新建一个分摊需要的模版
  isShowDelete: React.PropTypes.bool, //是否可删除明细
  expenseList: React.PropTypes.array, //费用明细列表
  currencyList: React.PropTypes.array, //可选币种列表
  currencyCode: React.PropTypes.string, //单据上币种控件的币种， 没有的情况下是本位币
  isHidePaymentType: React.PropTypes.bool, //支付方式是否隐藏
  params: React.PropTypes.object, //包含单据公司，单据部门，岗位信息
  onChange: React.PropTypes.func,
  handleAdd: React.PropTypes.func, //去添加费用类型
  handleOne: React.PropTypes.func, //点击切换一个费用明细
  disabledCurrency: React.PropTypes.bool, //币种是否不可更改
  defaultScrollTop: React.PropTypes.number, //滚动条初始滚动距离
};

ExpenseTypeBlock.defaultProps = {
  template: {},
  isShowDelete: false,
  expenseList: [],
  currencyList: [],
  currencyCode: '',
  isHidePaymentType: false,
  params: {},
  onChange: () => {},
  handleAdd: () => {},
  handleOne: () => {},
  disabledCurrency: false,
  defaultScrollTop: 0
};

export default connect(mapStateToProps)(ExpenseTypeBlock)
